package com.xpec.c4.h5net;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.cindy.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.infinispan.util.concurrent.ConcurrentHashSet;
import org.jboss.netty.channel.Channel;

public class H5XSENetSessionPool 
{
	/** log4j object */
	private static final Log log = LogFactory.getLog(H5XSENetSessionPool.class);
	
	//cindy-session pool
	private static final ConcurrentHashMap<Session, H5XSENetSession> sessions = new ConcurrentHashMap<Session, H5XSENetSession>();
	
	//netty-channel pool
	private static final ConcurrentHashMap<Channel, H5XSENetSession> sessions2 = new ConcurrentHashMap<Channel, H5XSENetSession>();
	
	// 暫時存放 沒xseNetSession的channel
	private static final Set<Channel> nullSessions = new ConcurrentHashSet<Channel>();
	
	
	public static H5XSENetSession getSession(Session session)
	{
		return sessions.get(session);
	}
	
	public static Collection<H5XSENetSession> getAllSession() {
		

		return sessions2.values();
	}
	
	/**
	 * 
	 * @return
	 */
	public static Collection<Channel> getNullSessions() {
		List list = new ArrayList();
		Collections.addAll(list, nullSessions.toArray());
		return list;
	}	
	
	public static H5XSENetSession getSession(Channel channel)
	{
		return sessions2.get(channel);
	}
	
	public static void addSession(Session session, H5XSENetSession xseSession)
	{
		sessions.put(session, xseSession);
	}
	
	public static void addSession(Channel channel, H5XSENetSession xseSession)
	{
		if(xseSession == null){
			// 沒有xseSession的channel要先另外存放
			nullSessions.add(channel);

			if (log.isInfoEnabled()) {
				log.info("add channel " + channel.getId() + " to nullSessions.");
			}
		}else{
			if(nullSessions.contains(channel)){
				// 有xseSession了channel之後就移掉
				nullSessions.remove(channel);

				if (log.isInfoEnabled()) {
					log.info("remove channel " + channel.getId() + " from nullSessions.");
				}
			}
			sessions2.put(channel, xseSession);
			
			if (log.isInfoEnabled()) {
				log.info("add channel " + channel.getId() + " to sessions2.");
			}
		}
	}
	
	public static H5XSENetSession removeSession(Session session)
	{
		return sessions.remove(session);
	}
	
	public static H5XSENetSession removeSession(Channel channel)
	{
		if(nullSessions.contains(channel)){
			// 至始至終都沒有xseSession的channel就移掉吧
			nullSessions.remove(channel);

			if (log.isInfoEnabled()) {
				log.info("remove channel "+ channel.getId() + " from nullSessions.");
			}
		}

		if (sessions2.containsKey(channel)) {
			if (log.isInfoEnabled()) {
				log.info("remove channel " + channel.getId() + " from sessions2.");
			}
		}

		return sessions2.remove(channel);
	}
}
